package com.jfinal.render;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import com.jfinal.log.Log;
import com.jfinal.poi.PoiExporter;

public class PoiRender extends Render {

	protected final Log LOG = Log.getLog(getClass());
	private final static String CONTENT_TYPE = "application/msexcel;charset=" + getEncoding();
	private List<?>[] data;
	private String[][] headers;
	private String[] sheetNames = new String[] { "sheet" };
	private int cellWidth = 4000;
	private String[][] columns;
	private String fileName = "file1.xlsx";
	private int headerRow;

	public PoiRender data(List<?>... data) {
		this.data = data;
		return this;
	}

	public PoiRender headers(String[]... headers) {
		this.headers = headers;
		return this;
	}

	public PoiRender headerRow(int headerRow) {
		this.headerRow = headerRow;
		return this;
	}

	public PoiRender columns(String[]... columns) {
		this.columns = columns;
		return this;
	}

	public PoiRender sheetName(String... sheetName) {
		this.sheetNames = sheetName;
		return this;
	}

	public PoiRender cellWidth(int cellWidth) {
		this.cellWidth = cellWidth;
		return this;
	}

	public PoiRender fileName(String fileName) {
		this.fileName = fileName;
		return this;
	}

	@Override
	public void render() {
		// response.reset();
		response.setHeader("Content-disposition", "attachment; filename=" + fileName);
		response.setContentType(CONTENT_TYPE);
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			PoiExporter poiExporter = PoiExporter.data(data).sheetNames(sheetNames).headerRow(headerRow).cellWidth(cellWidth);
			poiExporter.headers(headers).columns(columns);
			poiExporter.export().write(os);
		} catch (Exception e) {
			throw new RenderException(e);
		} finally {
			try {
				if (os != null) {
					os.flush();
					os.close();
				}
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
			}

		}
	}

}
